const pool = require('../config/db');

// 提交问卷回答
const submitSurveyResponse = async (req, res) => {
  try {
    const { survey_id, user_id, answers } = req.body;
    const ip_address = req.ip || req.connection.remoteAddress;
    
    // 验证必要参数
    if (!survey_id || !answers || !Array.isArray(answers)) {
      return res.status(400).json({
        code: 400,
        message: '参数错误'
      });
    }

    // 检查问卷是否存在且状态为active
    const [survey] = await pool.query(
      "SELECT * FROM surveys WHERE id = ? AND status = 'active'",
      [survey_id]
    );

    if (survey.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '问卷不存在或已关闭'
      });
    }

    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 创建回答记录
      const [responseResult] = await connection.query(
        'INSERT INTO responses (survey_id, user_id, ip_address) VALUES (?, ?, ?)',
        [survey_id, user_id || null, ip_address]
      );

      const response_id = responseResult.insertId;

      // 保存每个问题的回答
      for (const answer of answers) {
        const { question_id, content, selected_options } = answer;

        // 验证问题是否属于该问卷
        const [question] = await connection.query(
          'SELECT * FROM questions WHERE id = ? AND survey_id = ?',
          [question_id, survey_id]
        );

        if (question.length === 0) {
          throw new Error(`问题ID ${question_id} 不属于该问卷`);
        }

        // 插入回答
        const [answerResult] = await connection.query(
          'INSERT INTO answers (response_id, question_id, content) VALUES (?, ?, ?)',
          [response_id, question_id, content || null]
        );

        const answer_id = answerResult.insertId;

        // 如果是单选或多选题，保存选项
        if (selected_options && Array.isArray(selected_options) && selected_options.length > 0) {
          for (const option_id of selected_options) {
            // 验证选项是否属于该问题
            const [option] = await connection.query(
              'SELECT * FROM options WHERE id = ? AND question_id = ?',
              [option_id, question_id]
            );

            if (option.length === 0) {
              throw new Error(`选项ID ${option_id} 不属于问题 ${question_id}`);
            }

            // 插入选项回答
            await connection.query(
              'INSERT INTO option_answers (answer_id, option_id) VALUES (?, ?)',
              [answer_id, option_id]
            );
          }
        }
      }

      // 提交事务
      await connection.commit();

      res.json({
        code: 200,
        message: '提交成功',
        data: {
          response_id
        }
      });
    } catch (error) {
      // 回滚事务
      await connection.rollback();
      throw error;
    } finally {
      // 释放连接
      connection.release();
    }
  } catch (error) {
    console.error('提交问卷回答错误:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '服务器错误'
    });
  }
};

// 获取问卷回答统计
const getSurveyResults = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 验证id参数
    if (!id || isNaN(id)) {
      return res.status(400).json({
        code: 400,
        message: '无效的问卷ID'
      });
    }

    // 检查问卷是否存在
    const [survey] = await pool.query('SELECT * FROM surveys WHERE id = ?', [id]);
    if (survey.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '问卷不存在'
      });
    }

    // 获取问题列表
    const [questions] = await pool.query(
      'SELECT * FROM questions WHERE survey_id = ? ORDER BY order_num',
      [id]
    );

    // 获取回答总数
    const [totalResponses] = await pool.query(
      'SELECT COUNT(DISTINCT r.id) as total FROM responses r WHERE r.survey_id = ?',
      [id]
    );

    const total = totalResponses[0].total;

    // 处理每个问题的统计数据
    const results = [];
    for (const question of questions) {
      const questionResult = {
        id: question.id,
        type: question.type,
        content: question.content,
        total_answers: 0
      };

      // 获取该问题的回答数
      const [answerCount] = await pool.query(
        'SELECT COUNT(*) as count FROM answers WHERE question_id = ?',
        [question.id]
      );
      questionResult.total_answers = answerCount[0].count;

      // 根据问题类型处理不同的统计
      if (question.type === 'single' || question.type === 'multiple') {
        // 获取选项列表
        const [options] = await pool.query(
          'SELECT * FROM options WHERE question_id = ? ORDER BY order_num',
          [question.id]
        );

        // 获取每个选项的选择次数
        const optionsWithCount = [];
        for (const option of options) {
          const [optionCount] = await pool.query(
            `SELECT COUNT(*) as count 
             FROM option_answers oa 
             JOIN answers a ON oa.answer_id = a.id 
             WHERE oa.option_id = ? AND a.question_id = ?`,
            [option.id, question.id]
          );

          const count = optionCount[0].count;
          const percentage = total > 0 ? Math.round((count / total) * 100) : 0;

          optionsWithCount.push({
            id: option.id,
            content: option.content,
            count,
            percentage
          });
        }

        questionResult.options = optionsWithCount;
      } else if (question.type === 'rating') {
        // 处理评分题
        const [ratings] = await pool.query(
          `SELECT content, COUNT(*) as count 
           FROM answers 
           WHERE question_id = ? 
           GROUP BY content`,
          [question.id]
        );

        const ratingsMap = {};
        for (let i = 1; i <= 5; i++) {
          ratingsMap[i] = 0;
        }

        for (const rating of ratings) {
          if (rating.content && !isNaN(rating.content)) {
            ratingsMap[parseInt(rating.content)] = rating.count;
          }
        }

        questionResult.ratings = ratingsMap;
      } else {
        // 处理文本题
        const [textAnswers] = await pool.query(
          'SELECT content FROM answers WHERE question_id = ? AND content IS NOT NULL',
          [question.id]
        );

        questionResult.responses = textAnswers.map(answer => answer.content);
      }

      results.push(questionResult);
    }

    res.json({
      code: 200,
      message: '查询成功',
      data: {
        survey: survey[0],
        total_responses: total,
        results
      }
    });
  } catch (error) {
    console.error('获取问卷统计错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
};

module.exports = {
  submitSurveyResponse,
  getSurveyResults
};